package com.iot.protocol;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j
public class TcpClient implements AutoCloseable {
    private final String serverHost;
    private final int serverPort;
    private final Socket socket;
    private final PrintWriter out;
    private final BufferedReader in;
    private final ExecutorService executorService;
    private volatile boolean running;

    public TcpClient(String serverHost, int serverPort) throws IOException {
        this.serverHost = serverHost;
        this.serverPort = serverPort;
        this.socket = new Socket(serverHost, serverPort);
        this.out = new PrintWriter(socket.getOutputStream(), true);
        this.in = new BufferedReader(new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));
        this.executorService = Executors.newSingleThreadExecutor();
        this.running = true;
        log.info("TCP客户端已连接到服务器: {}:{}", serverHost, serverPort);
        
        // 启动接收消息的线程
        startReceiveThread();
    }

    private void startReceiveThread() {
        executorService.execute(() -> {
            try {
                String response;
                while (running && (response = in.readLine()) != null) {
                    log.info("收到服务器响应: {}", response);
                }
            } catch (IOException e) {
                if (running) {
                    log.error("接收消息时发生错误: {}", e.getMessage(), e);
                }
            }
        });
    }

    public void sendMessage(String message) {
        if (running) {
            out.println(message);
            log.info("已发送消息: {}", message);
        }
    }

    @Override
    public void close() {
        running = false;
        executorService.shutdown();
        try {
            if (out != null) out.close();
            if (in != null) in.close();
            if (socket != null && !socket.isClosed()) {
                socket.close();
            }
        } catch (IOException e) {
            log.error("关闭客户端时发生错误: {}", e.getMessage(), e);
        }
        log.info("TCP客户端已关闭");
    }

    public static void main(String[] args) {
        String serverHost = "localhost";
        int serverPort = 7050;

        try (TcpClient client = new TcpClient(serverHost, serverPort);
             Scanner scanner = new Scanner(System.in)) {
            
            System.out.println("TCP客户端已启动，请输入要发送的消息（输入'exit'退出）：");
            
            while (true) {
                String message = scanner.nextLine();
                if ("exit".equalsIgnoreCase(message)) {
                    break;
                }
                client.sendMessage(message);
            }
        } catch (IOException e) {
            log.error("TCP客户端发生错误: {}", e.getMessage(), e);
        }
    }
} 